import 'dart:async';

import 'package:flutter/cupertino.dart';
import 'package:get/get.dart';
import 'package:tiktokadult/hj_page/short_video/short_video_page.dart';
import 'package:tiktokadult/hj_page/short_video/view/short_progress_widget.dart';
import 'package:tiktokadult/tools_base/event_bus/event_bus_util.dart';
import 'package:tiktokadult/tools_base/event_bus/events.dart';
import 'package:tiktokadult/tools_base/global_store/local_ads_info_store.dart';
import 'package:tiktokadult/hj_utils/api_service/common_service.dart';
import 'package:tiktokadult/hj_utils/api_service/vid_service.dart';
import 'package:video_player/video_player.dart';

import '../../alert_business/video/recommend_video_res.dart';
import '../../hj_model/splash/ads_model.dart';
import '../../hj_model/video_model.dart';
import '../../tools_base/ad_insert_manager.dart';
import '../../tools_base/debug_log.dart';

class ShortVideoLogic extends GetxController with GetSingleTickerProviderStateMixin {
  static int tabMIndex = 3;
  static final List<Function(bool)> _playListenArr = [];

  static void addPlayListener(Function(bool) callback) {
    _playListenArr.add(callback);
  }

  static void removePlayListener(Function(bool) callback) {
    _playListenArr.remove(callback);
  }

  static void pauseAll() {
    for (Function(bool) callback in _playListenArr) {
      callback(false);
    }
  }

  static void play() {
    for (Function(bool) callback in _playListenArr) {
      callback(true);
    }
  }

  RxInt loadCount = 0.obs; // 0 loading 状态，第一次加载
  bool isLoadingData = false; // 显示倒数第6个视频的时候，主动翻页加载数据，isLoadingData防网络去重的作用
  RxInt pageViewIndex = 0.obs; // 显示的当前页数
  RxBool isShowMenu = true.obs;
  int currentPage = 1;
  bool hasNext = true;
  List<VideoModel>? videoList;
  final GlobalKey<ShortProgressWidgetState> progressKey = GlobalKey();
  late PageController pageController;
  final VideoListType fctType;
  VideoModel? secondVideoModel; //入参视频详情数据（需要通过视频详情接口获取视频权限）
  late StreamSubscription subscription;
  List<AdsInfoModel> get insertAdList => getAdvByTypeSync(12);
  ShortVideoLogic({
    this.currentPage = 1,
    this.hasNext = true,
    this.videoList,
    int pageIndex = 0,
    this.fctType = VideoListType.SECOND,
  }) {
    pageViewIndex.value = pageIndex;
  }

  @override
  void onInit() {
    subscription = eventBus.on<CollectStatusModel>(_followListenCallback);
    pageController = PageController(initialPage: pageViewIndex.value);
    super.onInit();
    WidgetsBinding.instance.addPostFrameCallback((timeStamp) async {
      if (fctType == VideoListType.SECOND) {
        if (videoList?.length == 1) {
          await _loadVideoDetail();
        } else {
          loadCount.value = 1;
        }
      }
      initData();
    });
  }

  void _followListenCallback(CollectStatusModel model) {
    // 当前ui状态通过CollectStatusWrapper已经处理了
    // 这里处理列表数据（只需要改数据），不需要刷新ui
    for (int i = 0; i < (videoList?.length ?? 0); i++) {
      VideoModel videoModel = videoList![i];
      if (model.isFollowed != null && model.uid == videoModel.publisher?.uid) {
        videoModel.publisher?.hasFollowed = model.isFollowed;
      }
    }
  }

  Future _loadVideoDetail() async {
    try {
      VideoModel? videoModel = await VidService.getVideoDetail(videoList?.first.id ?? '');
      if (videoModel != null) {
        secondVideoModel = videoModel;
        videoList?.removeAt(0);
        videoList?.insert(0, videoModel);
      }
    } catch (e) {
      debugLog(e.toString());
    }
    loadCount.value = 1;
  }

  void initData() {
    if (fctType == VideoListType.SECOND) {
      loadCount.value = 1;
      return;
    }
    loadCount.value = 0;
    loadData(isInit: true);
  }

  Future loadData({int page = 1, int pageSize = 12, bool isInit = false}) async {
    if (fctType == VideoListType.SECOND) {
      return;
    }
    if (isLoadingData) return;
    try {
      isLoadingData = false;
      RecommendListRes? resp;
      try {
        if (fctType == VideoListType.FOLLOW) {
          resp = await CommonService.fetchMyFollowDynamicList(page: page, size: pageSize, type: 1);
        } else if (fctType == VideoListType.Newest) {
          resp = await VidService.getShortNewestList(2, page, pageSize);
        } else {
          resp = await VidService.getRecommendVideoList(page, pageSize);
        }
      } catch (e) {
        debugLog(e);
      }
      List<VideoModel> list = resp?.vInfo ?? [];
      hasNext = resp?.hasNext ?? false;
      currentPage = page;
      videoList ??= [];
      if (page == 1) {
        videoList = [];
        if (isInit && secondVideoModel != null) {
          videoList?.add(secondVideoModel!);
        }
        setCurController(null);
        //_progressKey.currentState?.configVideoController(null);
        if (fctType == VideoListType.RECOMMEND && list.isNotEmpty == true) {
          // widget.callback?.call(list.first); // 更新用户信息
        }
      }
      videoList?.addAll(list);
      if (fctType == VideoListType.RECOMMEND) {
        videoList?.removeWhere((element) => element.isRandomAd());
        AdInsertManager.video(videoList ?? [], insertAdList, adGap: 6);
      }
    } catch (e) {
      videoList ??= [];
      debugLog("短视频列表获取失败:$e");
    }
    isLoadingData = false;
    loadCount.value = loadCount.value + 1;
  }

  void onPageChanged(int index) {
    if (pageViewIndex.value != index) {
      pageViewIndex.value = index;
      //widget.callback?.call(videoList![index]); //短视频右侧是用户页面, 更新用户信息,
    }
    if (videoList!.length - index <= 6) {
      loadData(page: currentPage + 1);
    }
  }

  void setCurController(VideoPlayerController? vc) {
    progressKey.currentState?.configVideoController(vc);
  }

  @override
  void dispose() {
    eventBus.off(subscription);
    super.dispose();
  }
}
